// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.security;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import lichen.LichenConstants;
import lichen.security.InvlidateRoleException;
import lichen.security.RequestedLoginException;
import lichen.security.Secured;
import lichen.security.SecurityChecker;

import org.apache.tapestry.Link;
import org.apache.tapestry.internal.services.LinkFactory;
import org.apache.tapestry.ioc.annotations.Inject;
import org.apache.tapestry.ioc.annotations.Symbol;
import org.apache.tapestry.services.RequestGlobals;

/**
 * 安全检测
 * @author Jun Tsai
 * @version $Revision$
 * @since 0.0.3
 */
public class SecurityCheckerImpl implements SecurityChecker {
	
	
	private RequestGlobals _requestGlobals;
	private LinkFactory _linkFactory;
	private String _loginPageName;

	public SecurityCheckerImpl(RequestGlobals requestGlobals,LinkFactory linkFactory,
			@Inject @Symbol(LichenConstants.USER_LOGIN_PAGE) String loginPageName){
		_requestGlobals = requestGlobals;
		_linkFactory = linkFactory;
		_loginPageName=loginPageName;
	}

	/**
	 * 
	 * @throws IOException 
	 * @see lichen.security.SecurityChecker#check(lichen.security.Secured)
	 * @since 0.0.3
	 */
	public void check(Secured secured) throws RequestedLoginException,InvlidateRoleException, IOException{
		HttpServletRequest request = _requestGlobals.getHTTPServletRequest();
		if(request.getUserPrincipal() == null){
			Link link = _linkFactory.createPageLink(_loginPageName, true, new Object[]{});
			_requestGlobals.getResponse().sendRedirect(link.toRedirectURI());
			return;
		}
		boolean result = false;
		for(String role:secured.value()){
			if(request.isUserInRole(role)){
				result =  true;
				break;
			}
		}
		if(!result){
			//TODO 增加跳转到不正确角色提示信息页面
			throw new InvlidateRoleException();
		}
	}

}
